package com.example.jetpackstu.ui.news

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.example.jetpackstu.R
import com.example.jetpackstu.databinding.FragmentDetailBinding

class DetailFragment : Fragment() {

    private var _binding: FragmentDetailBinding? = null

    private val binding get() = _binding!!

    private val mModel: DetailViewModel by viewModels()

    private val args: DetailFragmentArgs by navArgs()

    private val navController get() = findNavController()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DataBindingUtil.inflate(inflater, R.layout.fragment_detail, container, false)
        initView()
        initListener()
        initData()
        return binding.root
    }

    private fun initData() {
        mModel.getNews(args.id)
    }

    private fun initListener() {
        binding.btnSave.setOnClickListener {
            mModel.save()
            navController.navigateUp()
        }
    }

    private fun initView() {
        binding.model = mModel
        binding.lifecycleOwner = this
        mModel.news.observe(
            viewLifecycleOwner
        ) {
            it?.let {
                mModel.title.value = it.title
                mModel.content.value = it.content
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}